package com.course.controller.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.HttpMethod;
import com.aliyuncs.utils.StringUtils;

import com.course.confing.JwtUtils;
import com.course.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class LoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public void postHandle(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandle..");
    }

    @Override
    public void afterCompletion(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion..");
    }

    @Override//目标资源方法运行前运行，返回true；放行，返回false，不放行
    public boolean preHandle(jakarta.servlet.http.HttpServletRequest req, jakarta.servlet.http.HttpServletResponse resp, Object handler) throws Exception {
        //1.获取请求url
        String url=req.getRequestURI().toString();
        log.info("请求的url:{}",url);

        //2.判断请求url是否为login请求，是的话直接放行
        if(url.contains("login")){
            log.info("登录操作，放行");
            return true;
        }
        //如果发送的是option请求，先放行
        if (HttpMethod.OPTIONS.toString().equals(req.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            // 设置允许的源，根据实际情况调整，这里以通配符为例
            resp.setHeader("Access-Control-Allow-Origin", "*");

            // 设置允许的请求方法
            resp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");

            // 设置允许的请求头
            resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Token");

            // 如果需要携带凭证，设置该响应头
            // 注意：若设置为true，Access-Control-Allow-Origin不能设置为星号(*)
            // resp.setHeader("Access-Control-Allow-Credentials", "true");

            // 设置预检请求的有效期，单位为秒
            resp.setHeader("Access-Control-Max-Age", "6");
            return true;
        }
        //3.获取请求头的令牌(token)
        String jwt=req.getHeader("Token");
        //4.判断令牌是否为空
        if(StringUtils.isEmpty(jwt)){
            log.info("请求头的token为空，返回登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换为json格式
            String notlogin= JSONObject.toJSONString(error);
            resp.getWriter().write(notlogin);
            return false;
        }
        //5.解析token，如果解析失败，返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败,返回未登录错误信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换为json格式
            String notlogin=JSONObject.toJSONString(error);
            resp.getWriter().write(notlogin);
            return false;
        }
        //6.放行
        log.info("放行");
        return true;
    }

}
